package com.xxl.job.executor.sjbank.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.executor.sjbank.mapper.FiCreditcasesMapper;
import com.xxl.job.executor.sjbank.pojo.*;
import com.xxl.job.executor.sjbank.pojo.model.AutoAssign;
import com.xxl.job.executor.sjbank.service.CfgAssignratioService;
import com.xxl.job.executor.sjbank.service.CfgAssignsetService;
import com.xxl.job.executor.sjbank.mapper.CfgAssignsetMapper;
import com.xxl.job.executor.sjbank.service.FiCreditcasesHistService;
import com.xxl.job.executor.sjbank.service.FiCreditcasesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author tsu
 * @description 针对表【cfg_assignset】的数据库操作Service实现
 * @createDate 2024-04-01 11:56:59
 */
@Service
public class CfgAssignsetServiceImpl extends ServiceImpl<CfgAssignsetMapper, CfgAssignset>
        implements CfgAssignsetService {

    @Value("${ccrm.token}")
    private String cCrmToken;

    @Value("${ccrm.url}")
    private String cCrmurl;
    @Resource
    FiCreditcasesService fiCreditcasesService;
    @Resource
    CfgAssignratioService cfgAssignratioService;

    @Override
    public void autoAssign() {
        List<CfgAssignset> list = list(new QueryWrapper<CfgAssignset>()
                .eq("status", 1)
                .eq("startrun", 1));
        XxlJobHelper.log("XXXL-JOB-autoAssign 派工模版:" + list.size() + "条");
        // 自动派工
        assUsersToCases(list);
    }

    private void searchCases(List<CfgAssignset> list) {
        list.forEach(item -> {
            try {
                List<FiCreditcases> caselist = fiCreditcasesService.list(new QueryWrapper<FiCreditcases>()
                        .eq("sendtodept", item.getGrpid())
                        .eq("ccc", "Q")
                        .eq("status", 1));

                XxlJobHelper.log("XXL-JOB-autoAssign 符合条件的案件:" + caselist.size() + "条.");
                int count = caselist.size();
                if (count > 0) {
                    List<CfgAssignratio> users = cfgAssignratioService.list(new QueryWrapper<CfgAssignratio>()
                            .eq("grpid", item.getGrpid())
                            .orderByDesc("ratio"));
                    XxlJobHelper.log("XXL-JOB-autoAssign 被分配坐席:" + users.size() + "条.");
                    if (users.size() > 0) {
                        int mode = item.getModeval();
                        //assUsersToCases(caselist, users, mode);
                    } else {
                        XxlJobHelper.log("XXL-JOB-autoAssign 请配置自动派工坐席.");
                    }
                }
            } catch (Exception e) {
                XxlJobHelper.log("XXL-JOB-autoAssign, 错误日志:" + e + ">>>>>【异常列】：" + item);
            }
        });
    }

    private void assUsersToCases(List<CfgAssignset> list) {
        list.forEach(x -> {
            // 创建 JSON 对象
            JSONObject jsonObject = new JSONObject();
            // 固定字段
            jsonObject.put("taskid", x.getGrpid());
            jsonObject.put("tasktype", "ass");
            jsonObject.put("dismode", "1");
            String httpBody = jsonObject.toJSONString();
            XxlJobHelper.log("XXL-JOB-disUsersToCases, 请求参数:{}", httpBody);
            try {
                // 设置连接超时和响应超时
                Unirest.setTimeouts(30 * 60 * 1000, 60 * 1000);
                HttpResponse<JsonNode> jsonResponse = Unirest.post(cCrmurl + "/cpg/cpTaskDo")
                        .header("Content-Type", "application/json")
                        .header("Authorization", "Bearer " + cCrmToken)
                        .body(httpBody)
                        .asJson();
                // 获取响应体
                int status = jsonResponse.getStatus();
                JsonNode responseBody = jsonResponse.getBody();

                // 获取responseBody字段的值
                int code = responseBody.getObject().getInt("code");
                if (code == 200) {
                    XxlJobHelper.log("XXL-JOB-assUsersToCases, 自动派工成功");
                } else {
                    XxlJobHelper.log("XXL-JOB-assUsersToCases, 自动派工失败（状态码）：" + code);
                }
                XxlJobHelper.log("XXL-JOB-assUsersToCases, 调用Ccrm接口结束.status：{} >>>> responseBody：{}", status, responseBody);
            } catch (Exception e) {
                XxlJobHelper.log("XXL-JOB-assUsersToCases, 错误日志:" + e);
            }

        });
    }

    private void avgUsersToCases(List<FiCreditcases> caseList, List<CfgAssignratio> userList) {
        int totalCases = caseList.size(),
                totalUsers = userList.size(),
                casesPerUser = totalCases / totalUsers,   // 计算每个用户应该分配的案例数量
                extraCases = totalCases % totalUsers,     // 计算余下的案例数量
                caseIndex = 0;

        for (CfgAssignratio item : userList) {
            int assignedCases = casesPerUser + (extraCases > 0 ? 1 : 0); // 每个用户应该分配的案例数量
            for (int i = 0; i < assignedCases; i++) {
                caseList.get(caseIndex).setSendtousr(item.getUsrid());
                caseIndex++;
            }
            extraCases--; // 余下的案例数量减少
        }
    }
}
